package com.crocodile.game17.util;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * jdk 8
 */
public class JwtUtil {

    public static final long JWT_TTL = 60*60*1000L;
    public static final String JWT_KEY = "crocodiles";

    public static String getUUID(){
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        return token;
    }

    public static SecretKey generalKey(){
        byte[] encodeKey = Base64.getDecoder().decode(JWT_KEY);
        SecretKeySpec key = new SecretKeySpec(encodeKey, 0, encodeKey.length, "AES");

        return key;
    }

    public static Claims parseJwt(String jwt) throws Exception{

        SecretKey secretKey = generalKey();

        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

    /**
     * create jwt
     */

    public static String createJwt(String subject){
        JwtBuilder jwtBuilder = getJwtBuilder(subject, getUUID());

        return jwtBuilder.compact();
    }

    /**
     * 封装jwt
     */
    public static JwtBuilder getJwtBuilder(String subject,String UUid){
        SignatureAlgorithm algorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        long expMillis = nowMillis + JWT_TTL;
        Date expDate = new Date(expMillis);

        return Jwts.builder()
                .setId(UUid)
                .setSubject(subject)
                .setIssuer("crq")
                .setIssuedAt(now)
                .signWith(algorithm,secretKey)
                .setExpiration(expDate);
    }
}
